package cn.com.fssg.platform.base.handler.impl.cl.jiesuan;

import cn.com.fssg.platform.base.handler.InterfaceHandler;
import cn.com.fssg.platform.biz.BizUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @className: xunlianjiesuan
 * @description: TODO 变更结算
 * @author: xzm
 * @date: 2025/10/6
 **/
@Component
public class ClChangejiesuanCtl implements InterfaceHandler {

        //private NamedParameterJdbcTemplate jdbcTemplate = BizUtil.cur().tenantMainJdbcTemplate();
        @Autowired
        private NamedParameterJdbcTemplate jdbcTemplate;

        @Override
        @Transactional(rollbackFor = Exception.class)
        public Object run(HttpServletRequest request, JSONObject jsonObject) throws Exception {
            String type = jsonObject.getString("type");

            if(StringUtils.equals(type, "0")){
                Map<String, Object> jsQueryMap = new HashMap<>();
                String id = jsonObject.getString("id");
                jsQueryMap.put("id", id);
                String selectSql = "SELECT js.id,js.cjr_name,js.cjr_sex,js.cjr_birthday,js.cjr_minzu,js.cjr_hukou," +
                        "js.cjr_idcard,school,js.has_cjr_card,js.cjr_num,js.cjr_service_cat,js.shenpi_no,js.cjr_type," +
                        "js.cjr_cj_level,js.cjr_bx,js.cjr_jjqk,js.cjr_address,js.remark, " +
                        "cjr_jhr,js.jhr_idcard,js.cjr_jhr_gx,js.cjr_jhr_phone,yq.org_name,js.jiesuan_month," +
                        "js.jiesuan_total,yq.cjr_service_type AS dyq_cjr_service_type,yq.cjr_service_cat AS dyq_cjr_service_cat " +
                        "FROM cl_apply_change_org_jiesuan js LEFT JOIN cl_dyq yq on js.id = yq.jiesuan_id WHERE js.id =:id";


                //StringBuilder se  = new StringBuilder();
                //se.append(selectSql).append("WHERE js.id =  '").append(id).append("'");

                Map<String,Object> jsMap = jdbcTemplate.queryForMap(selectSql,jsQueryMap);
                List<Map<String,Object>> recordList = new ArrayList<>();
                recordList = selectRecord(id);
                String  jiesuan_month= jsMap.get("jiesuan_month").toString();
                int days = recordList.size();
                if(StringUtils.isNotBlank(jiesuan_month)){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(sdf.parse(jiesuan_month));
                    int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
                    jsMap.put("att_num",days+"/"+maxDay);
                }
                if(0!=days){
                    jsMap.put("total_date",getTotalDatePoor(recordList)+"小时");
                }else {
                    jsMap.put("total_date","0小时");
                }
                jsMap.put("record",recordList);
                return jsMap;
            }else if(StringUtils.equals(type, "1")){
                String shenpiNo = jsonObject.getString("shenpi_no");
                String cjrName = jsonObject.getString("cjr_name");
                String code = jsonObject.getString("dyq_code");//当前绑定代用券编号
                //绑定代用券，更新状态
                String userId = BizUtil.cur().curUserId();
                String logName = BizUtil.cur().curLoginname();

                String id = saveKfxljs(cjrName,shenpiNo);
                //修改代用券表状态及绑定参数
                int count = dyqBinding(userId,logName,code,id);
                return count;
            }else if(StringUtils.equals(type, "2")){
                //查找附件
                Map<String, Object> upMap = new HashMap<>();
                String id = jsonObject.getString("id");
                //添加考勤附件(该附件存入cl_dyq代用券表中)
                List<Map<String,Object>> files = selectAnnex(id,"service_detail_url");
                if(0!=files.size()){
                    upMap.put("service_detail_url",files);
                    String upDyqSql = "update cl_dyq set service_detail_url=:service_detail_url, remark=:remark  where id=:id";
                    //jdbcTemplate.update(upDyqSql, upMap);
                }
                //附件
                List<Map<String,Object>> fujian2List = selectAnnex(id,"fujian2");
                upMap.put("id",id);
                upMap.put("jiesuan_total",jsonObject.getString("jiesuan_total"));
                upMap.put("remark",jsonObject.getString("remark"));
                upMap.put("flow_status", "10");
                upMap.put("flow_status_describe", "审核中");
                upMap.put("update_by", BizUtil.cur().curUserId());
                upMap.put("update_time", new Date());
                String upSql = "update cl_apply_change_org_jiesuan set fujian2=:fujian2,jiesuan_total=:jiesuan_total,remark=:remark,update_by=:update_by,update_time=:update_time," +
                        "flow_status=:flow_status,flow_status_describe=:flow_status_describe where id=:id";
                jdbcTemplate.update(upSql, upMap);
            }else if(StringUtils.equals(type, "3")){
                //训练方式
                //查找附件
                Map<String, Object> upMap = new HashMap<>();
                String id = jsonObject.getString("id");
                String plan = jsonObject.getString("plan");
                upMap.put("id",id);
                upMap.put("plan",plan);
                //upMap.put("jiesuanTotal",jiesuanTotal);
                String upSql = "update cl_apply_xunlian_org_jiesuan set plan=:plan where id=:id";
                jdbcTemplate.update(upSql, upMap);

                upMap.put("plan_type",plan);
                String upDyqSql = "update cl_dyq set plan_type=:plan_type where jiesuan_id=:id";
                jdbcTemplate.update(upDyqSql, upMap);
            }
            return null;
        }

    /** 更新数据库数据 */
    public List<Map<String,Object>> selectRecord(String id) {
        Map<String, String> jsQueryMap = new HashMap<>();
        jsQueryMap.put("id", id);
        String recordSql = "SELECT qd.id AS qd_id,qd.org_id,qd.user_id,qd.history_id," +
                "qd.apply_type,qd.date,qd.status,qd.report_id,qd.org_address," +
                "qd.sign_in_time,qd.sign_out_time,qd.hexiao,qd.score,qd.warning_level," +
                "qd.warning_range,qd.plan_type,qd.parent_reason,qd.jiesuan_id," +
                "qd.parent_feedback,qd.parent_feedback_time,qd.create_by," +
                "qd.create_time,qd.update_by,qd.update_time,qd.remark,qd.del_flag,qd.bud_id,qd.dyq_id " +
                "FROM cl_sign_record qd WHERE qd.jiesuan_id = :id";
        List<Map<String,Object>> recordList = jdbcTemplate.queryForList(recordSql, jsQueryMap);
        return recordList;
    }
    /** 添加cl_apply_fuju_org_jiesuan */
    public String saveKfxljs(String cjrName, String shenpiNo) {
        //String id = BizUtil.cur().getSnowflakeIdStr();
        //获取辅具适配申请信息
        String queryZwWxUserSql = "select jhr_idcard,step,apply_status,shenpi_no,org_id,org_name,cjr_id,cjr_minzu,cjr_jjqk,cjr_name,cjr_sex,cjr_birthday,cjr_hukou,cjr_idcard,cjr_hukou_city," +
                "cjr_hukou_qu,cjr_hukou_street,cjr_hukou_shequ,has_cjr_card,cjr_num,cjr_type,cjr_type_name,cjr_cj_level,cjr_bx,cjr_address," +
                "cjr_jhr,cjr_jhr_gx,cjr_jhr_phone,cjr_jhr_user_id,cjr_service_type,cjr_service_cat,beizhu,cjr_hkb_url,cjr_zhengm," +
                "cjr_user_id,create_time,create_by,update_time,update_by,del_flag,version,remark,finish,process_instance_id,flow_business_key," +
                "flow_status,flow_status_describe,effect_from,effect_to,apply_time,reason,school,apply_way,submit_time " +
                "from cl_apply_change where shenpi_no = :shenpi_no and cjr_name = :cjr_name";

        Map<String, Object> param = new HashMap<>();
        param.put("shenpi_no", shenpiNo);
        param.put("cjr_name", cjrName);
        Map<String, Object> bgMaps = jdbcTemplate.queryForMap(queryZwWxUserSql, param);

        Map<String, Object> saveMap = new HashMap<>();
        String id = BizUtil.cur().getSnowflakeIdStr();

        saveMap.put("id", id);
        saveMap.put("create_by", BizUtil.cur().curUserId());
        saveMap.put("create_time", new Date());

        saveMap.put("shenpi_no",shenpiNo);
        saveMap.put("cjr_name",cjrName);
        saveMap.put("cjr_minzu",bgMaps.get("cjr_minzu"));
        saveMap.put("cjr_bx",bgMaps.get("cjr_bx"));
        saveMap.put("cjr_num",bgMaps.get("cjr_num"));
        saveMap.put("has_cjr_card",bgMaps.get("has_cjr_card"));
        saveMap.put("cjr_jjqk",bgMaps.get("cjr_jjqk"));
        saveMap.put("cjr_jhr",bgMaps.get("cjr_jhr"));
        saveMap.put("jhr_idcard",bgMaps.get("jhr_idcard"));
        saveMap.put("cjr_address",bgMaps.get("cjr_address"));
        saveMap.put("cjr_jhr_gx",bgMaps.get("cjr_jhr_gx"));
        saveMap.put("cjr_jhr_phone",bgMaps.get("cjr_jhr_phone"));
        saveMap.put("school",bgMaps.get("school"));
        saveMap.put("cjr_hkb_url",bgMaps.get("cjr_hkb_url"));
        saveMap.put("cjr_zhengm",bgMaps.get("cjr_zhengm"));
        saveMap.put("cjr_service_xiaojie",bgMaps.get("cjr_service_xiaojie"));
        saveMap.put("effect_from",bgMaps.get("effect_from"));
        saveMap.put("effect_to",bgMaps.get("effect_to"));
        saveMap.put("cjr_cj_level",bgMaps.get("cjr_cj_level"));
        saveMap.put("cjr_type",bgMaps.get("cjr_type"));
        saveMap.put("cjr_idcard",bgMaps.get("cjr_idcard"));
        saveMap.put("cjr_sex",bgMaps.get("cjr_sex"));
        saveMap.put("jiesuan_month",bgMaps.get("month"));
        saveMap.put("cjr_birthday",bgMaps.get("cjr_birthday"));
        saveMap.put("cjr_hukou",bgMaps.get("cjr_hukou"));
        saveMap.put("cjr_service_type",bgMaps.get("cjr_service_type"));
        saveMap.put("cjr_service_cat",bgMaps.get("cjr_service_cat"));
        saveMap.put("flow_status","00");
        saveMap.put("flow_status_describe","未提交");
        saveMap.put("del_flag","0");
        saveMap.put("apply_status", "训练中");

        String dep_id = BizUtil.cur().curUserDeptId();
        String dep_name = BizUtil.cur().curUserDeptName();
        saveMap.put("org_name",dep_name);
        saveMap.put("org_id",dep_id);
        //封装新增的sql语句
        List<String> fields = new ArrayList<>();
        List<String> placeholders = new ArrayList<>();

        StringBuffer sql = new StringBuffer();
        sql.append("INSERT INTO cl_apply_change_org_jiesuan (");
        saveMap.forEach((k, v) -> {
            if (v != null) {
                placeholders.add(":"+k);
                fields.add(k);
            }
        });
        sql.append(String.join(", ", fields)).append(") VALUES (").append(String.join(",",placeholders)).append(")");
        jdbcTemplate.update(sql.toString(), saveMap);
        return id;
    }
    /** 获取附件 */
    public List<Map<String,Object>> selectAnnex(String id,String field) {
        Map<String, String> jsQueryMap = new HashMap<>();
        jsQueryMap.put("form_code", "Form20251012163921");
        jsQueryMap.put("key_value", id);
        jsQueryMap.put("form_field", field);
        String recordSql = "SELECT id,form_code,key_value,form_field,file_name,alias_name," +
                "file_path,ext_name,file_size,user_id,user_realname " +
                "FROM pxone.cfg_data_form_file_info WHERE form_code =:form_code and key_value =:key_value and form_field =:form_field";
        List<Map<String,Object>> recordList = jdbcTemplate.queryForList(recordSql, jsQueryMap);
        return recordList;
    }
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 86400000L;
        long nh = 3600000L;
        long nm = 60000L;
        long diff = endDate.getTime() - nowDate.getTime();
        long day = diff / nd;
        long hour = diff % nd / nh;
        long min = diff % nd % nh / nm;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    public static String getTotalDatePoor(List<Map<String,Object>> dateList) {
        long nd = 86400000L;
        long nh = 3600000L;
        long nm = 60000L;
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Long> times = new ArrayList<>();
        dateList.forEach(s->{
            Date sign_in_time = (Date) s.get("sign_in_time");
            Date sign_out_time = (Date) s.get("sign_out_time");
            long diff = sign_out_time.getTime() - sign_in_time.getTime();
            times.add(diff);
        });
        long sum = times.stream().mapToLong(Long::longValue).sum();
        long day = sum / nh;
        return day+"";
    }

    /** 添加cl_dyq */
    public int dyqBinding(String org_id, String org_name, String code, String id) {

        Map<String, Object> upMap = new HashMap<>();
        String dep_id = BizUtil.cur().curUserDeptId();
        //String dep_name = "部门测试";
        String dep_name = BizUtil.cur().curUserDeptName();
        //机构id
        upMap.put("org_id",dep_id);
        //机构名称
        upMap.put("org_name",dep_name);

        upMap.put("bind_time",new Date());
        upMap.put("jiesuan_id", id);
        upMap.put("code",code);
        String upSql = "update cl_dyq set org_id=:org_id, org_name=:org_name, bind_time=:bind_time,jiesuan_id=:jiesuan_id where code=:code";

        return jdbcTemplate.update(upSql, upMap);
    }
}
